package net.discard.controller;

import lombok.extern.slf4j.Slf4j;
import net.discard.dao.ActivityRegistrationRepository;
import net.discard.dao.ActivityRepository;
import net.discard.dao.UserRepository;
import net.discard.model.Activity;
import net.discard.model.ActivityRegistration;
import net.discard.model.domian.ResponseVo;
import net.discard.model.vo.ActivityVo;
import net.discard.util.GsonUtils;
import org.apache.commons.lang.IncompleteArgumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Stream;

import static net.discard.model.domian.ResponseVo.SUCCESS;

/**
 * @Author: Discard
 * @Date: 2021/2/4 4:51 下午
 */
@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController {

    @Autowired
    ActivityRepository activityRepository;

    @Autowired
    ActivityRegistrationRepository activityRegistrationRepository;

    @Autowired
    UserRepository userRepository;

    @GetMapping(value = "/getAll")
    public String getAllActivity() {
        List list = activityRepository.findAll();
        return new ResponseVo(ActivityVo.voList(list)).toString();
    }

    @GetMapping(value = "/hot")
    public String getHotActivity() {
        List list = activityRepository.findByWeightGreaterThanOrderByWeight(0);
        return new ResponseVo(ActivityVo.voList(list)).toString();
    }

    @GetMapping(value = "/info/{activityId}")
    public String getActivityInfo(@PathVariable long activityId) {
        Activity activity = activityRepository.findById(activityId)
                .orElse(null);
        return new ResponseVo(new ActivityVo(activity)).toString();
    }

    @PostMapping("registration/{activeId},{userId}")
    public ResponseVo activeRegistration(@PathVariable long activeId,
                                         @PathVariable long userId) {
        return SUCCESS(Stream.of(0)
                .peek(e -> activityRegistrationRepository.findByUserIdAndActivityId(userId, activeId)
                        .ifPresent(i -> {
                            throw new IllegalArgumentException("您已经报名该活动");
                        }))
                .peek(e -> activityRepository.findById(activeId).orElseThrow(() ->
                        new IllegalArgumentException("活动" + activeId + "不存在")))
                .peek(e -> userRepository.findById(userId).orElseThrow(() ->
                        new IllegalArgumentException("用户" + userId + "不存在")))
                .map(s -> activityRegistrationRepository.save(ActivityRegistration.builder()
                        .activityId(activeId)
                        .userId(userId)
                        .build()))
                .peek(e -> log.info("add activity registration info: {}", GsonUtils.toJson(e)))
                .findFirst()
                .orElse(null)
        );
    }

}
